package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.ParamCategory;
import com.zhentao.pojo.ParamDefinition;
import com.zhentao.service.ParamCategoryService;
import com.zhentao.service.ParamDefinitionService;
import com.zhentao.util.Result;
import com.zhentao.vo.ParamDefinitionVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 手机端API控制器
 * 为手机端提供简化的API接口
 *
 * @author zhentao
 * @since 2024-08-28
 */
@Tag(name = "手机端API", description = "专为手机端优化的API接口")
@RestController
@RequestMapping("/mobile")
@RequiredArgsConstructor
@Slf4j
public class MobileApiController {

    private final ParamCategoryService paramCategoryService;
    private final ParamDefinitionService paramDefinitionService;

    /**
     * 获取参数分类列表（简化版）
     */
    @Operation(summary = "获取参数分类", description = "获取参数分类的简化列表")
    @GetMapping("/categories")
    public Result getCategories() {
        long startTime = System.currentTimeMillis();
        log.info("开始获取参数分类列表");
        try {
            List<ParamCategory> categories = paramCategoryService.list(
                    new LambdaQueryWrapper<ParamCategory>()
                            .eq(ParamCategory::getStatus, 1)
                            .orderByAsc(ParamCategory::getSortOrder)
                            .orderByAsc(ParamCategory::getCreateTime)
            );
            
            if (categories.isEmpty()) {
                return Result.OK(new ArrayList<>());
            }
            
            // 批量获取子分类数量（DB分组聚合，避免加载全部子分类）
            List<Long> categoryIds = categories.stream().map(ParamCategory::getId).collect(java.util.stream.Collectors.toList());
            Map<Long, Integer> childCountMap = new HashMap<>();
            List<Map<String, Object>> childCountRows = paramCategoryService.getBaseMapper().selectMaps(
                    new QueryWrapper<ParamCategory>()
                            .select("parent_id AS pid", "COUNT(*) AS cnt")
                            .in("parent_id", categoryIds)
                            .groupBy("parent_id")
            );
            for (Map<String, Object> row : childCountRows) {
                Long pid = row.get("pid") == null ? null : ((Number) row.get("pid")).longValue();
                Integer cnt = row.get("cnt") == null ? 0 : ((Number) row.get("cnt")).intValue();
                if (pid != null) {
                    childCountMap.put(pid, cnt);
                }
            }
            
            // 批量获取参数数量统计（DB分组聚合，避免加载全部参数行）
            Map<Long, Integer> paramCountMap = new HashMap<>();
            try {
                List<Map<String, Object>> paramCountRows = paramDefinitionService.getBaseMapper().selectMaps(
                        new QueryWrapper<ParamDefinition>()
                                .select("category_id AS cid", "COUNT(*) AS cnt")
                                .in("category_id", categoryIds)
                                .groupBy("category_id")
                );
                for (Map<String, Object> row : paramCountRows) {
                    Long cid = row.get("cid") == null ? null : ((Number) row.get("cid")).longValue();
                    Integer cnt = row.get("cnt") == null ? 0 : ((Number) row.get("cnt")).intValue();
                    if (cid != null) {
                        paramCountMap.put(cid, cnt);
                    }
                }
                // 补齐没有参数的分类
                for (Long categoryId : categoryIds) {
                    paramCountMap.putIfAbsent(categoryId, 0);
                }
            } catch (Exception e) {
                log.warn("批量获取参数统计失败，使用默认值: {}", e.getMessage());
                for (Long categoryId : categoryIds) {
                    paramCountMap.put(categoryId, 0);
                }
            }
            
            List<Map<String, Object>> list = new ArrayList<>();
            for (ParamCategory c : categories) {
                Map<String, Object> m = new HashMap<>();
                m.put("id", c.getId());
                m.put("name", c.getCategoryName());
                m.put("description", c.getDescription());
                
                int childCount = childCountMap.getOrDefault(c.getId(), 0);
                int paramCount = paramCountMap.getOrDefault(c.getId(), 0);
                int count = paramCount > 0 ? paramCount : childCount;
                
                m.put("childCount", childCount);
                m.put("paramCount", paramCount);
                m.put("count", count);
                list.add(m);
            }
            long endTime = System.currentTimeMillis();
            log.info("获取参数分类列表完成，耗时: {}ms, 返回数量: {}", endTime - startTime, list.size());
            return Result.OK(list);
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.error("获取参数分类列表失败，耗时: {}ms", endTime - startTime, e);
            return Result.ERROR("获取参数分类列表失败");
        }
    }

    /**
     * 获取参数定义列表（简化版）
     */
    @Operation(summary = "获取参数定义", description = "获取参数定义的简化列表")
    @GetMapping("/definitions")
    public Result getDefinitions(@RequestParam(value = "categoryId", required = false) Long categoryId) {
        try {
            List<ParamDefinition> list = paramDefinitionService.list(
                    new LambdaQueryWrapper<ParamDefinition>()
                            .eq(categoryId != null, ParamDefinition::getCategoryId, categoryId)
                            .orderByDesc(ParamDefinition::getCreateTime)
            );
            List<Map<String, Object>> res = new ArrayList<>();
            for (ParamDefinition d : list) {
                Map<String, Object> m = new HashMap<>();
                m.put("id", d.getId());
                m.put("paramKey", d.getParamKey());
                m.put("paramName", d.getParamName());
                m.put("paramType", d.getDataType());
                m.put("defaultValue", d.getDefaultValue());
                m.put("categoryId", d.getCategoryId());
                res.add(m);
            }
            return Result.OK(res);
        } catch (Exception e) {
            log.error("获取参数定义列表失败", e);
            return Result.ERROR("获取参数定义列表失败");
        }
    }

    /**
     * 获取参数详情
     */
    @Operation(summary = "获取参数详情", description = "获取指定参数的详细信息")
    @GetMapping("/definitions/{id}")
    public Result getDefinitionDetail(@PathVariable Long id) {
        try {
            ParamDefinitionVO vo = paramDefinitionService.getParamDefinitionDetail(id);
            if (vo == null) {
                return Result.ERROR("未找到参数");
            }
            return Result.OK(vo);
        } catch (Exception e) {
            log.error("获取参数详情失败，参数ID: {}", id, e);
            return Result.ERROR("获取参数详情失败");
        }
    }

    /**
     * 搜索参数
     */
    @Operation(summary = "搜索参数", description = "根据关键词搜索参数")
    @GetMapping("/search")
    public Result searchParameters(@RequestParam("keyword") String keyword) {
        try {
            if (!StringUtils.hasText(keyword)) {
                return Result.OK(Collections.emptyList());
            }
            // 真实库模糊搜索 param_key/param_name
            List<ParamDefinition> list = paramDefinitionService.list(
                    new LambdaQueryWrapper<ParamDefinition>()
                            .like(ParamDefinition::getParamKey, keyword)
                            .or()
                            .like(ParamDefinition::getParamName, keyword)
                            .orderByDesc(ParamDefinition::getCreateTime)
            );
            List<Map<String, Object>> results = new ArrayList<>();
            for (ParamDefinition d : list) {
                Map<String, Object> m = new HashMap<>();
                m.put("id", d.getId());
                m.put("paramKey", d.getParamKey());
                m.put("paramName", d.getParamName());
                m.put("type", d.getDataType());
                results.add(m);
            }
            return Result.OK(results);
        } catch (Exception e) {
            log.error("搜索参数失败，关键词: {}", keyword, e);
            return Result.ERROR("搜索参数失败");
        }
    }

    /**
     * 获取通知列表
     */
    @Operation(summary = "获取通知列表", description = "获取系统通知消息")
    @GetMapping("/notifications")
    public Result getNotifications() {
        try {
            return Result.OK(Collections.emptyList());
        } catch (Exception e) {
            log.error("获取通知列表失败", e);
            return Result.ERROR("获取通知列表失败");
        }
    }

    /**
     * 标记通知为已读
     */
    @Operation(summary = "标记通知已读", description = "将指定通知标记为已读")
    @PostMapping("/notifications/{id}/read")
    public Result markNotificationAsRead(@PathVariable Long id) {
        try {
            // 这里应该更新数据库中的通知状态
            log.info("标记通知为已读成功，通知ID: {}", id);
            return Result.OK();
        } catch (Exception e) {
            log.error("标记通知为已读失败，通知ID: {}", id, e);
            return Result.ERROR("标记通知为已读失败");
        }
    }
}


